import pymysql


class DBUtil():
    conn = None

    @classmethod
    def __get_conn(cls):
        """私有类方法,类内部可以访问,外部不能看到"""
        if cls.conn is None:
            cls.conn = pymysql.connect(host='211.103.136.244', user='student',
                                password='iHRM_student_2021',
                                port=7061, database='ihrm',charset='utf8')
        return cls.conn
    #   不能放入if代码块中
    @classmethod
    def __close_conn(cls):
        if cls.conn:
            # 如果连接为非空,则执行关闭连接的代码
            cls.conn.close()
            cls.conn = None

    @classmethod
    def get_one(cls, sql):
        cursor=None
        res=None
        try:
            cursor=cls.__get_conn().cursor()
            cursor.execute(sql)
            res=cursor.fetchone()
        except Exception as err:
            print('执行查询sql语句出错:',err)
            raise err
        finally:
            cursor.close()
            cls.__close_conn()
            # 查询结果不存在时返回None值
            return res

    @classmethod
    def uid_db(cls, sql):
        cursor=None
        res=None
        try:
            cursor=cls.__get_conn().cursor()
            cursor.execute(sql)
            res=cursor.rowcount
            cls.__get_conn().commit()
        except Exception as err:
            print('操作出错啦:',err)
            cls.__get_conn().rollback()
            raise err
        finally:
            cursor.close()
            cls.__close_conn()
            return res
if __name__ == '__main__':
    sql_query="select * from t_book limit 1"
    print(DBUtil.get_one(sql_query))
    # sql_delete="delete from t_book where title = '困困巨兽'"
    # print(DBUtil.uid_db(sql_delete))
    sql_insert="insert into t_book(id,title,pub_date) values (9527,'演员的自我修养','2021-12-12')"
    print(DBUtil.uid_db(sql_insert))